package main

import (
	"io"

	"tunnel_manager/core"

	"github.com/quic-go/quic-go"
)

// init 初始化core包的函数注入
func init() {
	// 注入WriteMessage实现
	core.WriteMessage = func(stream quic.Stream, msg *core.TunnelMessage) error {
		// 转换为main包的TunnelMessage
		mainMsg := &TunnelMessage{
			Magic:        ProtocolMagic,
			Version:      msg.Version,
			MessageType:  msg.MessageType,
			ProtocolType: ProtocolType(msg.ProtocolType),
			TunnelID:     msg.TunnelID,
			RequestID:    msg.RequestID,
			ConnectionID: msg.ConnectionID,
			BodyLength:   msg.BodyLength,
			Body:         msg.Body,
		}
		return mainMsg.Write(&stream)
	}

	// 注入ReadMessage实现
	core.ReadMessage = func(r io.Reader) (*core.TunnelMessage, error) {
		// 使用main包的ReadMessage
		mainMsg, err := ReadMessage(r)
		if err != nil {
			return nil, err
		}

		// 转换为core包的TunnelMessage
		return &core.TunnelMessage{
			Magic:        mainMsg.Magic,
			Version:      mainMsg.Version,
			MessageType:  mainMsg.MessageType,
			ProtocolType: core.ProtocolType(mainMsg.ProtocolType),
			TunnelID:     mainMsg.TunnelID,
			RequestID:    mainMsg.RequestID,
			ConnectionID: mainMsg.ConnectionID,
			BodyLength:   mainMsg.BodyLength,
			Reserved:     mainMsg.Reserved,
			Body:         mainMsg.Body,
		}, nil
	}
}
